﻿// <file>
//     <copyright see="prj:///doc/copyright.txt"/>
//     <license see="prj:///doc/license.txt"/>
//     <owner name="Matthew Ward" email="mrward@users.sourceforge.net"/>
//     <version>$Revision: 2076 $</version>
// </file>

using System;
using NUnit.Core;

namespace NUnit.ConsoleRunner
{
	/// <summary>
	/// Filters tests based on the namespace they are in.
	/// </summary>
	[Serializable]
	public class NamespaceFilter : Filter
	{
		string testCaseNamespacePrefix;
		string ns;
		
		/// <summary>
		/// Creates a new instance of the NamespaceFilter.
		/// </summary>
		/// <param name="ns">The root namespace that a test
		/// has to belong to in order to be run.</param>
		public NamespaceFilter(string ns)
		{
			this.ns = ns;
			testCaseNamespacePrefix = String.Concat(ns, ".");
		}
		
		/// <summary>
		/// If the TestSuite is a NamespaceSuite then if the
		/// namespace matches our filter it will be passed. Note that this
		/// method will pass namespaces that could be a parent namespace for
		/// the namespace being filtered (e.g. For a filter of Projects.Tests
		/// then if the TestSuite.FullName is Projects then this will pass). 
		/// This has to be done otherwise NUnit will exclude child 
		/// namespaces that may pass our filter. This method will also
		/// pass any child namespaces that have a parent namespace that
		/// matches our filter.
		/// </summary>
		public override bool Pass(TestSuite suite)
		{
			if (suite != null) {
				NamespaceSuite namespaceSuite = suite as NamespaceSuite;
				if (namespaceSuite != null) {
					string fullName = namespaceSuite.FullName;
					return ns.StartsWith(fullName) || fullName.StartsWith(ns);
				}
				return true;
			}
			return false;
		}
		
		/// <summary>
		/// Only those tests that are in the namespace defined by 
		/// this filter are passed.
		/// </summary>
		public override bool Pass(TestCase test)
		{
			if (test != null) {
				return test.FullName.StartsWith(testCaseNamespacePrefix);
			}
			return false;
		}
	}
}
